<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试答题 - 学生端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        .exam-container {
            display: flex;
            min-height: 100vh;
        }

        /* 左侧题目导航 */
        .question-sidebar {
            width: 280px;
            background: white;
            border-right: 1px solid #e8eaed;
            padding: 20px;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            z-index: 100;
        }

        .sidebar-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e8eaed;
        }

        .exam-title {
            font-size: 16px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 8px;
        }

        .exam-meta {
            font-size: 12px;
            color: #666;
            display: flex;
            gap: 15px;
        }

        .timer-section {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 20px;
            text-align: center;
        }

        .timer-label {
            font-size: 12px;
            color: #856404;
            margin-bottom: 4px;
        }

        .timer-display {
            font-size: 18px;
            font-weight: 600;
            color: #856404;
            font-family: 'Courier New', monospace;
        }

        .timer-warning {
            background: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }

        .progress-section {
            margin-bottom: 20px;
        }

        .progress-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 8px;
        }

        .progress-bar {
            width: 100%;
            height: 6px;
            background: #e8eaed;
            border-radius: 3px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4CAF50, #8BC34A);
            border-radius: 3px;
            transition: width 0.3s ease;
        }

        .question-nav {
            margin-bottom: 20px;
        }

        .nav-title {
            font-size: 14px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 12px;
        }

        .question-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 8px;
        }

        .question-nav-item {
            width: 40px;
            height: 40px;
            border: 2px solid #e8eaed;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
            background: white;
        }

        .question-nav-item:hover {
            border-color: #4285f4;
            background: #f8f9ff;
        }

        .question-nav-item.answered {
            background: #4CAF50;
            color: white;
            border-color: #4CAF50;
        }

        .question-nav-item.current {
            background: #4285f4;
            color: white;
            border-color: #4285f4;
        }
        
        .question-nav-item.unanswered {
            background: #dc3545;
            color: white;
            border-color: #dc3545;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }

        .submit-section {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e8eaed;
        }

        .btn-submit {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-submit:hover {
            background: linear-gradient(135deg, #c82333, #bd2130);
            transform: translateY(-1px);
        }

        /* 右侧主内容区 */
        .main-content {
            flex: 1;
            margin-left: 280px;
            padding: 20px;
        }

        .exam-header {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .header-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .question-counter {
            font-size: 16px;
            font-weight: 600;
            color: #1a1a1a;
        }

        .nav-buttons {
            display: flex;
            gap: 10px;
        }

        .nav-btn {
            padding: 8px 16px;
            border: 1px solid #e8eaed;
            border-radius: 6px;
            background: white;
            color: #333;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
        }

        .nav-btn:hover:not(:disabled) {
            border-color: #4285f4;
            background: #f8f9ff;
        }

        .nav-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .question-card {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .question-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        .question-type-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
            background: #e3f2fd;
            color: #1976d2;
            border: 1px solid #2196f3;
        }

        .question-type-badge.type-single {
            background: #e3f2fd;
            color: #1976d2;
            border-color: #2196f3;
        }

        .question-type-badge.type-multiple {
            background: #f3e5f5;
            color: #7b1fa2;
            border-color: #9c27b0;
        }

        .question-type-badge.type-true-false {
            background: #e8f5e8;
            color: #388e3c;
            border-color: #4caf50;
        }

        .type-icon {
            font-size: 16px;
        }

        .type-text {
            font-size: 14px;
        }

        .question-content {
            font-size: 18px;
            line-height: 1.6;
            color: #1a1a1a;
            margin-bottom: 25px;
            font-weight: 500;
        }

        .options-container {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .option-item {
            display: flex;
            align-items: center;
            padding: 16px 20px;
            border: 2px solid #e8eaed;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s ease;
            background: white;
        }

        .option-item:hover {
            border-color: #4285f4;
            background: #f8f9ff;
        }

        .option-item.selected {
            border-color: #4285f4;
            background: #e3f2fd;
        }

        .option-item.multiple-choice.selected {
            border-color: #4caf50;
            background: #e8f5e8;
        }

        .option-label {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #f5f5f5;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-right: 15px;
            transition: all 0.2s ease;
        }

        .option-item.selected .option-label {
            background: #4285f4;
            color: white;
        }

        .option-text {
            flex: 1;
            font-size: 16px;
            line-height: 1.4;
        }

        /* 提交确认模态框 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 30px;
            max-width: 500px;
            width: 90%;
            text-align: center;
        }

        .modal-title {
            font-size: 20px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 20px;
        }

        .submit-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin: 20px 0;
        }

        .stat-item {
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .stat-number {
            font-size: 24px;
            font-weight: 600;
            color: #4285f4;
        }

        .stat-label {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
        }

        .modal-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 25px;
        }

        .modal-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .btn-cancel {
            background: #6c757d;
            color: white;
        }

        .btn-confirm {
            background: #dc3545;
            color: white;
        }

        .modal-btn:hover {
            transform: translateY(-1px);
        }

        /* 自动保存指示器 */
        .auto-save-indicator {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 12px;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .auto-save-indicator.show {
            opacity: 1;
        }

        .auto-save-indicator.saving {
            background: #2196F3;
        }

        .auto-save-indicator.saved {
            background: #4CAF50;
        }

        .auto-save-indicator.error {
            background: #F44336;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .question-sidebar {
                width: 100%;
                position: relative;
                height: auto;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .question-grid {
                grid-template-columns: repeat(4, 1fr);
            }
        }
    </style>
</head>
<body>
    <div class="exam-container">
        <!-- 左侧题目导航 -->
        <div class="question-sidebar">
            <div class="sidebar-header">
                <div class="exam-title" id="examTitle">考试标题</div>
                <div class="exam-meta">
                    <span>共 <span id="totalQuestions">0</span> 题</span>
                    <span><span id="timeLimit">0</span> 分钟</span>
                </div>
            </div>

            <div class="timer-section" id="timerSection">
                <div class="timer-label">剩余时间</div>
                <div class="timer-display" id="timerDisplay">00:00</div>
            </div>

            <div class="progress-section">
                <div class="progress-label">答题进度</div>
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill" style="width: 0%"></div>
                </div>
            </div>

            <div class="question-nav">
                <div class="nav-title">题目导航</div>
                <div class="question-grid" id="questionGrid">
                    <!-- 题目导航将在这里动态生成 -->
                </div>
            </div>

            <div class="submit-section">
                <button class="btn-submit" onclick="showSubmitModal()">提交考试</button>
            </div>
        </div>

        <!-- 右侧主内容区 -->
        <div class="main-content">
            <div class="exam-header">
                <div class="header-top">
                    <div class="question-counter">
                        第 <span id="currentQuestionNum">1</span> 题，共 <span id="totalQuestionsHeader">0</span> 题
                    </div>
                    <div class="nav-buttons">
                        <button class="nav-btn" id="prevBtn" onclick="previousQuestion()">上一题</button>
                        <button class="nav-btn" id="nextBtn" onclick="nextQuestion()">下一题</button>
                    </div>
                </div>
            </div>

            <div class="question-card">
                <div class="question-header">
                    <div class="question-type-badge" id="questionTypeBadge">
                        <span class="type-icon">🔘</span>
                        <span class="type-text">单选题</span>
                    </div>
                </div>
                <div class="question-content" id="questionContent">
                    正在加载题目...
                </div>
                <div class="options-container" id="optionsContainer">
                    <!-- 选项将在这里动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 提交确认模态框 -->
    <div class="modal-overlay" id="submitModal">
        <div class="modal-content">
            <div class="modal-title">确认提交考试</div>
            <div class="submit-stats">
                <div class="stat-item">
                    <div class="stat-number" id="answeredCount">0</div>
                    <div class="stat-label">已答题</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="unansweredCount">0</div>
                    <div class="stat-label">未答题</div>
                </div>
            </div>
            <p style="color: #666; margin: 20px 0;">提交后将无法修改答案，确定要提交吗？</p>
            <div class="modal-buttons">
                <button class="modal-btn btn-cancel" onclick="hideSubmitModal()">取消</button>
                <button class="modal-btn btn-confirm" onclick="submitExam()">确认提交</button>
            </div>
        </div>
    </div>

    <!-- 自动保存指示器 -->
    <div class="auto-save-indicator" id="autoSaveIndicator">
        <span id="autoSaveText">自动保存中...</span>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentExam = null;
        let questions = [];
        let answers = {};
        let currentQuestionIndex = 0;
        let timeRemaining = 0;
        let timerInterval = null;
        let autoSaveInterval = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadExamData();
        });

        // 检查用户认证状态
        function checkAuth() {
            const user = UserManager.getCurrentUser();
            if (!user || user.role !== 2) {
                Message.error('请先登录学生账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
        }

        // 加载考试数据
        function loadExamData() {
            const examData = sessionStorage.getItem('currentExam');
            if (!examData) {
                Message.error('考试数据不存在，请重新开始考试');
                setTimeout(() => {
                    window.location.href = 'exams.html';
                }, 1500);
                return;
            }

            try {
                const data = JSON.parse(examData);
                console.log('考试数据:', data); // 调试日志
                
                currentExam = data.exam;
                questions = data.questions;
                
                if (!questions || questions.length === 0) {
                    Message.error('没有获取到考试题目');
                    setTimeout(() => {
                        window.location.href = 'exams.html';
                    }, 1500);
                    return;
                }
                
                // 初始化答案对象 - 使用前端ID作为键
                questions.forEach((question, index) => {
                    const frontendId = `q_${index}`; // 前端ID：q_0, q_1, q_2...
                    const backendId = question.id; // 后端ID：数据库中的实际ID
                    
                    // 创建题目映射
                    question.frontendId = frontendId;
                    question.backendId = backendId;
                    
                    // 使用前端ID作为答案对象的键
                    answers[frontendId] = '';
                    
                    console.log('初始化答案对象 - 前端ID:', frontendId, '后端ID:', backendId, '题目内容:', question.content);
                });
                console.log('初始化完成 - 答案对象:', answers);
                
                // 验证题目ID映射
                console.log('=== 题目ID映射验证 ===');
                questions.forEach((question, index) => {
                    console.log(`题目 ${index + 1}: 前端ID=${question.frontendId}, 后端ID=${question.backendId}, 内容="${question.content}"`);
                });
                console.log('=== 验证结束 ===');

                // 设置考试信息
                document.getElementById('examTitle').textContent = currentExam.title || '考试';
                document.getElementById('totalQuestions').textContent = questions.length;
                document.getElementById('totalQuestionsHeader').textContent = questions.length;
                document.getElementById('timeLimit').textContent = currentExam.timeLimit || 60;

                // 设置计时器
                timeRemaining = (currentExam.timeLimit || 60) * 60; // 转换为秒
                startTimer();

                // 开始自动保存
                startAutoSave();

                // 渲染题目导航
                renderQuestionNavigation();
                
                // 显示第一题
                showQuestion(0);

                // 更新进度
                updateProgress();
                
                Message.success('考试加载成功，开始答题！');
            } catch (error) {
                console.error('解析考试数据失败:', error);
                Message.error('考试数据格式错误');
                setTimeout(() => {
                    window.location.href = 'exams.html';
                }, 1500);
            }
        }

        // 开始计时器
        function startTimer() {
            updateTimerDisplay();
            timerInterval = setInterval(() => {
                timeRemaining--;
                updateTimerDisplay();
                
                if (timeRemaining <= 0) {
                    clearInterval(timerInterval);
                    Message.warning('考试时间到，自动提交考试');
                    submitExam();
                }
            }, 1000);
        }

        // 更新计时器显示
        function updateTimerDisplay() {
            const minutes = Math.floor(timeRemaining / 60);
            const seconds = timeRemaining % 60;
            const display = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            const timerElement = document.getElementById('timerDisplay');
            timerElement.textContent = display;
            
            // 时间不足5分钟时显示警告
            if (timeRemaining <= 300) { // 5分钟
                document.getElementById('timerSection').classList.add('timer-warning');
            }
        }

        // 开始自动保存
        function startAutoSave() {
            // 每30秒自动保存一次
            autoSaveInterval = setInterval(() => {
                autoSaveAnswers();
            }, 30000);
        }

        // 自动保存答案
        async function autoSaveAnswers() {
            try {
                console.log('=== 自动保存开始 ===');
                console.log('当前考试ID:', currentExam ? currentExam.id : '未定义');
                console.log('当前答案对象:', answers);
                console.log('题目数量:', questions.length);
                
                showAutoSaveIndicator('saving', '自动保存中...');
                
                // 将前端ID转换为后端ID
                const backendAnswers = {};
                questions.forEach((question, index) => {
                    const frontendAnswer = answers[question.frontendId];
                    console.log(`题目 ${index + 1}: 前端ID=${question.frontendId}, 后端ID=${question.backendId}, 答案="${frontendAnswer}"`);
                    if (frontendAnswer && frontendAnswer.trim() !== '') {
                        backendAnswers[question.backendId] = frontendAnswer;
                    }
                });
                
                console.log('自动保存 - 前端答案对象:', answers);
                console.log('自动保存 - 后端答案对象:', backendAnswers);
                console.log('后端答案数量:', Object.keys(backendAnswers).length);
                
                if (Object.keys(backendAnswers).length === 0) {
                    console.log('警告: 没有答案需要保存');
                    showAutoSaveIndicator('saved', '无答案需要保存');
                    return;
                }
                
                // 调用后端API保存答案
                console.log('调用后端API...');
                const response = await API.post(`/exam/auto-save/${currentExam.id}`, { answers: backendAnswers });
                console.log('后端API响应:', response);
                
                showAutoSaveIndicator('saved', '已自动保存');
                console.log('=== 自动保存完成 ===');
                
            } catch (error) {
                console.error('自动保存失败:', error);
                console.error('错误详情:', error.message);
                showAutoSaveIndicator('error', '保存失败');
            }
        }

        // 显示自动保存指示器
        function showAutoSaveIndicator(type, text) {
            const indicator = document.getElementById('autoSaveIndicator');
            const textElement = document.getElementById('autoSaveText');
            
            indicator.className = `auto-save-indicator show ${type}`;
            textElement.textContent = text;
            
            // 3秒后隐藏
            setTimeout(() => {
                indicator.classList.remove('show');
            }, 3000);
        }

        // 更新答题进度
        function updateProgress() {
            const answeredCount = Object.values(answers).filter(answer => answer).length;
            const totalCount = questions.length;
            const percentage = totalCount > 0 ? (answeredCount / totalCount) * 100 : 0;
            
            document.getElementById('progressFill').style.width = `${percentage}%`;
        }

        // 渲染题目导航
        function renderQuestionNavigation() {
            const questionGrid = document.getElementById('questionGrid');
            questionGrid.innerHTML = questions.map((question, index) => {
                // 检查是否已作答
                const answer = answers[question.frontendId];
                const isAnswered = answer && answer.trim() !== '';
                const answerClass = isAnswered ? 'answered' : 'unanswered';
                
                return `
                    <div class="question-nav-item ${index === 0 ? 'current' : ''} ${answerClass}" 
                         onclick="goToQuestion(${index})">
                        ${index + 1}
                    </div>
                `;
            }).join('');
        }

        // 显示指定题目
        function showQuestion(index) {
            if (index < 0 || index >= questions.length) return;
            
            currentQuestionIndex = index;
            const question = questions[index];
            
            console.log('=== 显示题目调试 ===');
            console.log('题目索引:', index);
            console.log('前端ID:', question.frontendId);
            console.log('后端ID:', question.backendId);
            console.log('题目内容:', question.content);
            console.log('题目类型:', question.type);
            console.log('当前答案对象:', answers);
            console.log('当前题目的答案:', answers[question.frontendId]);
            console.log('=== 结束调试 ===');
            
            // 更新导航按钮状态
            document.getElementById('prevBtn').disabled = index === 0;
            document.getElementById('nextBtn').disabled = index === questions.length - 1;
            
            // 更新题目导航
            document.querySelectorAll('.question-nav-item').forEach((item, i) => {
                item.classList.remove('current');
                if (i === index) {
                    item.classList.add('current');
                }
            });

            // 更新题目编号
            document.getElementById('currentQuestionNum').textContent = index + 1;

            // 更新题型标签
            updateQuestionTypeBadge(question.type || 1);

            // 渲染题目内容
            document.getElementById('questionContent').textContent = question.content || '题目内容加载中...';
            
            // 渲染选项
            const optionsContainer = document.getElementById('optionsContainer');
            const questionType = question.type || 1; // 默认单选题
            
            if (questionType === 3) {
                // 判断题
                optionsContainer.innerHTML = `
                    <div class="option-item ${answers[question.frontendId] === 'T' ? 'selected' : ''}" 
                         onclick="selectOption('${question.frontendId}', 'T')">
                        <div class="option-label">✓</div>
                        <div class="option-text">正确</div>
                    </div>
                    <div class="option-item ${answers[question.frontendId] === 'F' ? 'selected' : ''}" 
                         onclick="selectOption('${question.frontendId}', 'F')">
                        <div class="option-label">✗</div>
                        <div class="option-text">错误</div>
                    </div>
                `;
            } else if (questionType === 2) {
                // 多选题
                const options = [
                    { key: 'A', value: question.optionA },
                    { key: 'B', value: question.optionB },
                    { key: 'C', value: question.optionC },
                    { key: 'D', value: question.optionD }
                ].filter(opt => opt.value); // 只显示有内容的选项
                
                optionsContainer.innerHTML = options.map(option => {
                    const isSelected = answers[question.frontendId] && answers[question.frontendId].includes(option.key);
                    return `
                        <div class="option-item multiple-choice ${isSelected ? 'selected' : ''}" 
                             onclick="selectMultipleOption('${question.frontendId}', '${option.key}')">
                            <div class="option-label">${option.key}</div>
                            <div class="option-text">${option.value || '选项加载中...'}</div>
                        </div>
                    `;
                }).join('');
            } else {
                // 单选题
                const options = [
                    { key: 'A', value: question.optionA },
                    { key: 'B', value: question.optionB },
                    { key: 'C', value: question.optionC },
                    { key: 'D', value: question.optionD }
                ].filter(opt => opt.value); // 只显示有内容的选项
                
                optionsContainer.innerHTML = options.map(option => `
                    <div class="option-item ${answers[question.frontendId] === option.key ? 'selected' : ''}" 
                         onclick="selectOption('${question.frontendId}', '${option.key}')">
                        <div class="option-label">${option.key}</div>
                        <div class="option-text">${option.value || '选项加载中...'}</div>
                    </div>
                `).join('');
            }
        }

        // 更新题型标签
        function updateQuestionTypeBadge(questionType) {
            const badge = document.getElementById('questionTypeBadge');
            const iconSpan = badge.querySelector('.type-icon');
            const textSpan = badge.querySelector('.type-text');
            
            // 清除所有类型样式
            badge.className = 'question-type-badge';
            
            switch (questionType) {
                case 1: // 单选题
                    iconSpan.textContent = '🔘';
                    textSpan.textContent = '单选题';
                    badge.classList.add('type-single');
                    break;
                case 2: // 多选题
                    iconSpan.textContent = '☑️';
                    textSpan.textContent = '多选题';
                    badge.classList.add('type-multiple');
                    break;
                case 3: // 判断题
                    iconSpan.textContent = '✅';
                    textSpan.textContent = '判断题';
                    badge.classList.add('type-true-false');
                    break;
                default:
                    iconSpan.textContent = '🔘';
                    textSpan.textContent = '单选题';
                    badge.classList.add('type-single');
                    break;
            }
        }

        // 选择答案（单选题和判断题）
        function selectOption(frontendId, option) {
            console.log('=== selectOption 开始 ===');
            console.log('接收到的参数 - frontendId:', frontendId, 'option:', option);
            console.log('当前 answers 对象:', answers);
            
            answers[frontendId] = option;
            
            // 获取对应的题目信息
            const question = questions.find(q => q.frontendId === frontendId);
            
            console.log('=== 选择答案调试 ===');
            console.log('前端ID:', frontendId);
            console.log('后端ID:', question ? question.backendId : '未知');
            console.log('选择的答案:', option);
            console.log('更新后的答案对象:', answers);
            console.log('答案对象键:', Object.keys(answers));
            console.log('=== 结束调试 ===');
            
            // 更新选项显示
            const container = document.getElementById('optionsContainer');
            if (container) {
                container.querySelectorAll('.option-item').forEach(item => {
                    item.classList.remove('selected');
                });
                
                const selectedItem = container.querySelector(`[onclick="selectOption('${frontendId}', '${option}')"]`);
                if (selectedItem) {
                    selectedItem.classList.add('selected');
                    console.log('选项已选中:', option);
                } else {
                    console.log('未找到对应的选项元素');
                }
            } else {
                console.log('未找到 optionsContainer 元素');
            }
            
            // 更新题目导航状态
            updateQuestionNavigation();
            
            // 更新进度
            updateProgress();
            
            // 立即自动保存
            console.log('开始自动保存...');
            autoSaveAnswers();
        }

        // 选择多选题答案
        function selectMultipleOption(frontendId, option) {
            if (!answers[frontendId]) {
                answers[frontendId] = '';
            }
            
            let currentAnswer = answers[frontendId];
            if (currentAnswer.includes(option)) {
                // 如果已选择，则取消选择
                currentAnswer = currentAnswer.replace(option, '');
            } else {
                // 如果未选择，则添加选择
                currentAnswer += option;
            }
            
            // 按字母顺序排序
            currentAnswer = currentAnswer.split('').sort().join('');
            answers[frontendId] = currentAnswer;
            
            // 获取对应的题目信息
            const question = questions.find(q => q.frontendId === frontendId);
            
            console.log('=== 选择多选题答案调试 ===');
            console.log('前端ID:', frontendId);
            console.log('后端ID:', question ? question.backendId : '未知');
            console.log('选择的答案:', option);
            console.log('当前答案字符串:', currentAnswer);
            console.log('当前答案对象:', answers);
            console.log('答案对象键:', Object.keys(answers));
            console.log('=== 结束调试 ===');
            
            // 更新选项显示
            const container = document.getElementById('optionsContainer');
            container.querySelectorAll('.option-item').forEach(item => {
                item.classList.remove('selected');
            });
            
            // 标记所有选中的选项
            for (let i = 0; i < currentAnswer.length; i++) {
                const selectedItem = container.querySelector(`[onclick="selectMultipleOption('${frontendId}', '${currentAnswer[i]}')"]`);
                if (selectedItem) {
                    selectedItem.classList.add('selected');
                }
            }
            
            // 更新题目导航状态
            updateQuestionNavigation();
            
            // 更新进度
            updateProgress();
            
            // 立即自动保存
            autoSaveAnswers();
        }

        // 更新题目导航状态
        function updateQuestionNavigation() {
            document.querySelectorAll('.question-nav-item').forEach((item, index) => {
                const question = questions[index];
                item.classList.remove('answered', 'unanswered');
                const answer = answers[question.frontendId];
                if (answer && answer.trim() !== '') {
                    item.classList.add('answered');
                } else {
                    item.classList.add('unanswered');
                }
            });
        }

        // 跳转到指定题目
        function goToQuestion(index) {
            showQuestion(index);
        }

        // 高亮显示未作答的题目
        function highlightUnansweredQuestions() {
            const unansweredQuestions = [];
            questions.forEach((question, index) => {
                const answer = answers[question.frontendId];
                if (!answer || answer.trim() === '') {
                    unansweredQuestions.push(index);
                }
            });
            
            if (unansweredQuestions.length > 0) {
                // 跳转到第一个未作答的题目
                showQuestion(unansweredQuestions[0]);
                
                // 高亮显示所有未作答的题目
                unansweredQuestions.forEach(index => {
                    const navItem = document.querySelectorAll('.question-nav-item')[index];
                    if (navItem) {
                        navItem.style.animation = 'pulse 1s infinite';
                        setTimeout(() => {
                            navItem.style.animation = '';
                        }, 5000);
                    }
                });
            }
        }

        // 上一题
        function previousQuestion() {
            if (currentQuestionIndex > 0) {
                showQuestion(currentQuestionIndex - 1);
            }
        }

        // 下一题
        function nextQuestion() {
            if (currentQuestionIndex < questions.length - 1) {
                showQuestion(currentQuestionIndex + 1);
            }
        }

        // 显示提交确认模态框
        function showSubmitModal() {
            const answeredCount = Object.values(answers).filter(answer => answer).length;
            const unansweredCount = questions.length - answeredCount;
            
            document.getElementById('answeredCount').textContent = answeredCount;
            document.getElementById('unansweredCount').textContent = unansweredCount;
            document.getElementById('submitModal').style.display = 'flex';
        }

        // 隐藏提交确认模态框
        function hideSubmitModal() {
            document.getElementById('submitModal').style.display = 'none';
        }

        // 检查答案完整性
        function checkAnswerCompleteness() {
            console.log('=== 答案完整性检查 ===');
            let answeredCount = 0;
            let unansweredCount = 0;
            
            questions.forEach((question, index) => {
                const answer = answers[question.frontendId];
                if (answer && answer.trim() !== '') {
                    answeredCount++;
                    console.log(`题目 ${index + 1} (前端ID: ${question.frontendId}, 后端ID: ${question.backendId}): 已作答 - ${answer}`);
                } else {
                    unansweredCount++;
                    console.log(`题目 ${index + 1} (前端ID: ${question.frontendId}, 后端ID: ${question.backendId}): 未作答`);
                }
            });
            
            console.log(`总计: ${answeredCount} 题已作答, ${unansweredCount} 题未作答`);
            console.log('=== 检查结束 ===');
            
            return { answeredCount, unansweredCount };
        }

        // 提交考试
        async function submitExam() {
            try {
                // 检查答案完整性
                const completeness = checkAnswerCompleteness();
                
                // 如果有未作答的题目，提示用户
                if (completeness.unansweredCount > 0) {
                    // 高亮显示未作答的题目
                    highlightUnansweredQuestions();
                    
                    const confirmSubmit = confirm(`您还有 ${completeness.unansweredCount} 道题目未作答，确定要提交考试吗？\n\n未作答的题目将按错误处理。\n\n建议先完成所有题目再提交。`);
                    if (!confirmSubmit) {
                        return;
                    }
                }
                
                // 清除计时器和自动保存
                if (timerInterval) {
                    clearInterval(timerInterval);
                }
                if (autoSaveInterval) {
                    clearInterval(autoSaveInterval);
                }

                Message.info('正在提交考试...');
                
                // 将前端ID转换为后端ID
                const backendAnswers = {};
                questions.forEach(question => {
                    const frontendAnswer = answers[question.frontendId];
                    if (frontendAnswer && frontendAnswer.trim() !== '') {
                        backendAnswers[question.backendId] = frontendAnswer;
                    }
                });
                
                console.log('提交考试 - 考试ID:', currentExam.id);
                console.log('提交考试 - 前端答案对象:', answers);
                console.log('提交考试 - 后端答案对象:', backendAnswers);
                console.log('提交考试 - 前端答案数量:', Object.keys(answers).length);
                console.log('提交考试 - 后端答案数量:', Object.keys(backendAnswers).length);
                
                const response = await API.post(`/exam/submit/${currentExam.id}`, {
                    answers: backendAnswers
                });
                
                if (response.success) {
                    // 清除考试数据
                    sessionStorage.removeItem('currentExam');
                    
                    // 显示成绩
                    const score = response.score;
                    const total = response.totalQuestions;
                    const percentage = response.percentage;
                    
                    Message.success(`考试提交成功！得分：${score}/${total} (${percentage.toFixed(1)}%)`);
                    
                    // 跳转到考试记录页面
                    setTimeout(() => {
                        window.location.href = 'exam-records.html';
                    }, 2000);
                } else {
                    Message.error(response.message || '提交考试失败');
                }
            } catch (error) {
                console.error('提交考试失败:', error);
                Message.error('提交考试失败，请稍后重试');
            }
        }

        // 页面卸载时清除计时器
        window.addEventListener('beforeunload', function() {
            if (timerInterval) {
                clearInterval(timerInterval);
            }
            if (autoSaveInterval) {
                clearInterval(autoSaveInterval);
            }
        });
    </script>
</body>
</html>
